package 每日一题;

public class Date1125 {

    StringBuilder list = new StringBuilder();
    boolean end = false;
    boolean first = true;

    public static void main(String[] args) {
        Date1125 test = new Date1125();
        System.out.println(test.sortString1("aaaabbbbcccc"));;
    }

    public String sortString(String s) {

        /**
         * 自解：将s的每个字符串存入 然后轮流顺序 倒叙遍历 知道s为空
         * 死循环了！！！
         */
        if (end){//从那个方法调进来 return回去就到相对应的位置
            return s;
        }

        int[] con = new int[26];

        if (first){
            for (int i=0;i<s.length();i++){
                con[s.charAt(i)-'a'] +=1;
            }
            first = false;
        }
        getBigger(con);

        return "";
    }

    public void getBigger(int[] con){


        if (judge(con)){
            end = true;
            sortString(list.toString());

        }
        for (int i=0;i<26;i++){
            if (con[i] !=0){
                list.append((char)('a'+i));
                con[i]--;
            }
        }

        getSmaller(con);


      //  return list;
    }

    public void getSmaller(int[] con){
        if (judge(con)){
            end = true;
            sortString(list.toString());

        }

        for (int i=25;i>=0;i--){
            if (con[i] !=0){
                list.append((char)('a'+i));
                con[i]--;
            }
        }
        getBigger(con);
    }

    public boolean judge (int[] con){
        for (int i=0;i<con.length;i++){
            if (con[i] != 0){
                return false;
            }
        }
        return true;
    }

    /**
     * 同上面思路
     * @param s
     * @return
     */
    public String sortString1(String s) {

        int[] con = new int[26];
        char[] chars = s.toCharArray();
        for (int i=0;i<s.length();i++){
            con[chars[i]-'a'] +=1;
        }

        StringBuilder stringBuilder = new StringBuilder();
        while (stringBuilder.length() != s.length()){
            for (int i=0;i<26;i++){
                if (con[i] > 0){
                    stringBuilder.append((char)('a'+i));
                    con[i]--;
                }
            }


            for (int i=25;i>=0;i--){
                if (con[i] > 0){
                    stringBuilder.append((char)('a'+i));
                    con[i]--;
                }
            }
        }

        return stringBuilder.toString();
    }
}
